<template>
  <div style="height: 100%">
    <mTableLayout>
      <template #form>
        <mForm :configs="formConfigs" :formData="formInline" @search="onSearch">
          <template #department_id>
            <el-select
              v-model="formInline.department_id"
              placeholder="请选择部门"
              style="width: 100%"
            >
              <el-option
                v-for="item in departmentsListData"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </template>
          <template #role_id>
            <el-select
              v-model="formInline.role_id"
              placeholder="请选择角色"
              style="width: 100%"
            >
              <el-option
                v-for="item in rolesListData"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </template>
          <template #real_name>
            <el-input v-model="formInline.real_name" placeholder="请输入姓名" />
          </template>
          <template #phone>
            <el-input v-model="formInline.phone" placeholder="请输入手机号" />
          </template>
          <template #user_name>
            <el-input v-model="formInline.user_name" placeholder="请输入账号" />
          </template>
        </mForm>
      </template>
      <template #op-btn>
        <!-- 新增 删除 -->
        <el-button v-if="isCreate == 1" type="primary" @click="handleAdd()" icon="Plus"
          >新增</el-button
        >
        <el-button v-if="isDelete == 1" type="danger"
          @click="batchDelete"
          :disabled="selectionData.length === 0"
          icon="Delete"
          >删除</el-button
        >
      </template>
      <template #table>
        <mTable
          ref="mTableRef"
          :tableHeader="tableHeader"
          :tableData="tableData"
          :adapter="tableAjax"
          @selection-change="handleSelectionChange"
        >
          <template #handle="{ row }">
            <el-button type="primary" link @click="handleAssignProject(row)">
              授权
            </el-button>
          </template>
          <template #status="{ row }">
            <img
              :src="row.status === 1 ? qiyongImg : jinyongImg"
              class="status-icon"
              @click="toggleStatus(row)"
            />
          </template>
          <template #default="{ row }">
            <img v-if="isEdit == 1 && row.id != '1'"
              @click="handleEdit(row)"
              src="@/assets/images/icon/update_icon.png"
              class="update_icon"
            />
            <img v-if="isDelete == 1 && row.id != '1'"
                 @click="handleDelete(row.id)"
              src="@/assets/images/icon/delete_icon.png"
              class="delete_icon"
            />
          </template>
        </mTable>
      </template>
    </mTableLayout>

    <el-dialog
      v-model="updateVisible"
      :title="updateForm.id ? '修改角色' : '新增角色'"
      width="500px"
    >
      <el-form
        :model="updateForm"
        :rules="updateRules"
        ref="formRef"
        label-width="100px"
      >
        <el-form-item label="姓名" prop="real_name">
          <el-input v-model="updateForm.real_name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="updateForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="账户名" prop="user_name">
          <el-input v-model="updateForm.user_name" placeholder="请输入账户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="updateForm.password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="部门" prop="department_id">
          <el-select
            v-model="updateForm.department_id"
            placeholder="请选择部门"
            style="width: 100%"
          >
            <el-option
              v-for="item in departmentsListData"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="角色" prop="role_id">
          <el-select
            v-model="updateForm.role_id"
            placeholder="请选择角色"
            style="width: 100%"
          >
            <el-option
              v-for="item in rolesListData"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="updateForm.status">
            <el-radio :value="1">启用</el-radio>
            <el-radio :value="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="updateVisible = false">取消</el-button>
          <el-button type="primary" @click="saveUpdate"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 用户表单（新增/编辑） -->
    <AddUser ref="addUserRef" @refresh="mTableRef.fetchData(true)" />
  </div>
</template>
<script setup>
import { tableHeader, formConfigs } from "./config";

import { ref, onMounted, reactive } from "vue";
import AddUser from "./addUser.vue";

import {
  userAdd,
  userUpdatePassword,
  userDetail,
  userDel,
  userList,
  userUpdate,
  rolesList,
  departmentsList,
} from "@/api";
import { ElMessage, ElMessageBox } from "element-plus";

// 导入状态图片
import qiyongImg from "@/assets/images/icon/qiyong.png";
import jinyongImg from "@/assets/images/icon/jinyong.png";
import {useAppStore} from "@/stores/app.js";

const appStore = useAppStore();
const isCreate = ref(null);
const isDelete = ref(null);
const isEdit = ref(null);

const departmentsListData = ref([]);
const rolesListData = ref([]);
const formInline = reactive({
  real_name: "",
  user_name: "",
  phone: "",
  department_id: "",
  role_id: "",
});

const getdepartmentsList = () => {
  departmentsList({ pageSize: 20, page: 1, is_not_limit: 1 }).then((res) => {
    if (res.code == 0) {
      departmentsListData.value = res.data || [];
    }
  });
};

const getrolesList = () => {
  rolesList({ pageSize: 20, page: 1, is_not_limit: 1 }).then((res) => {
    if (res.code == 0) {
      rolesListData.value = res.data || [];
    }
  });
};

const onSearch = (data) => {
  console.log(data.value);
  // formInline = data.value;
  mTableRef.value.fetchData(true);
};

const mTableRef = ref(null);
const total = ref(0);
const updateVisible = ref(false);
const assignRef = ref(null);
const addUserRef = ref(null);
const updateForm = ref({
  id: null,
  user_name: null,
  phone: null,
  real_name: null,
  department_id: null,
  role_id: null,
  password: null,
  status: null,
});
const updateRules = ref({
  user_name: [{ required: true, message: "请输入账号名", trigger: "blur" }],
  phone: [{ required: true, message: "请输入手机号", trigger: "blur" }],
  real_name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
  status: [{ required: true, message: "请选择账户状态", trigger: "blur" }],
  department_id: [{ required: true, message: "请选择部门", trigger: "blur" }],
  role_id: [{ required: true, message: "请选择角色", trigger: "blur" }],
});
const selectionData = ref([]);

const tableData = ref([]);
onMounted(() => {

  if(appStore.userInfo?.roles?.user_manage?.indexOf("create") >= 0){
    isCreate.value = 1;
  }else{
    isCreate.value = 0;
  }

  if(appStore.userInfo?.roles?.user_manage?.indexOf("edit") >= 0){
    isEdit.value = 1;
  }else{
    isEdit.value = 0;
  }

  if(appStore.userInfo?.roles?.user_manage?.indexOf("delete") >= 0){
    isDelete.value = 1;
  }else{
    isDelete.value = 0;
  }


  mTableRef.value.fetchData(true);

  getdepartmentsList();
  getrolesList();
});
// 列表请求
const tableAjax = async ({ pageSize, currentPage }) => {
  let o = {
    pageSize,
    page: currentPage,
    ...formInline,
  };
  let res = await userList(o);
  console.log(res, "res");
  if (res.code == 0) {
    tableData.value = res.data;
    total.value = res.count || 0;
  }
  return {
    data: res.data,
    total: res.count || 0,
  };
};

const handleAssignProject = (row) => {
  console.log(row);
  assignRef.value.openDrawer(row);
};

const handleAdd = () => {
  addUserRef.value.openAddDrawer();
};

const handleEdit = (row) => {
  addUserRef.value.openEditDrawer(row);
};

const handleUpdate = (row) => {
  if (row) {
    updateForm.value = { ...row };
  } else {
    updateForm.value = {
      id: null,
      name: null,
      description: null,
    };
  }
  updateVisible.value = true;
};

const batchDelete = () => {
  handleDelete(selectionData.value.map((item) => item.id).join(","));
};

// 批量+单个处理删除
const handleDelete = (ids) => {
  ElMessageBox.confirm("确定删除吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    userDel({ id: ids }).then((res) => {
      if (res.code == 0) {
        mTableRef.value.fetchData(true);
        ElMessage.success("删除成功");
      }
    });
  });
};

const saveUpdate = () => {
  console.log(updateForm.value);
  if (updateForm.value.id) {
    updateRoleFun(updateForm.value);
  } else {
    addRoleFun(updateForm.value);
  }
};
const updateRoleFun = (data) => {
  let o = {
    id: data.id,
    name: data.name,
    description: data.description,
  };
  updateRole(o).then((res) => {
    if (res.code == 0) {
      updateVisible.value = false;
      mTableRef.value.fetchData(true);
      ElMessage.success("修改成功");
    }
    console.log(res);
  });
};
const addRoleFun = (data) => {
  console.log(data);
  addRole(data).then((res) => {
    if (res.code == 0) {
      updateVisible.value = false;
      mTableRef.value.fetchData(true);
      ElMessage.success("新增成功");
    }
  });
};
// 页面上勾选的数据选择
const handleSelectionChange = (val) => {
  selectionData.value = val;
};

// 切换用户状态
const toggleStatus = (row) => {
  const newStatus = row.status === 1 ? 0 : 1;
  const statusText = newStatus === 1 ? "启用" : "禁用";

  ElMessageBox.confirm(`确定要${statusText}该用户吗？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    userUpdate({
      id: row.id,
      status: newStatus,
    }).then((res) => {
      if (res.code == 0) {
        mTableRef.value.fetchData(true);
        ElMessage.success(`${statusText}成功`);
      }
    });
  });
};
</script>
<style scoped lang="scss">
:deep(.demo-form-inline) {
  .el-input,
  .el-select {
    width: 220px;
  }
}

.status-icon {
  width: 50px;
  vertical-align: middle;
  cursor: pointer;
}
</style>
